define(['jquery'], function ($) {
    //保存信息到隐藏的input标签中，供后台生成使用
    var save = function (iframe, plugins, callback) {
        var type = plugins.data('type');
        var options = $(plugins).find("div.options input[type='hidden']");
        var label = $(plugins).find("label.plugins-label");
        var attr = $(iframe).find("form").serializeArray();
        var data = [];
        data['options'] = [];
        $.each(attr, function (name, value) {
            var name = this.name;
            var value = this.value;
            var pattern = /\[\w.*\]/;//排除value为数组的情况
            if (!pattern.test(name))
            {
                if (name === 'title')
                {
                    $(label).text(value);
                }
                $(options).attr('data-' + name, value);
                data[name] = value;
            }
        });
        //控件类型另存
        $(options).attr('data-type', type);
        getNewPlugins(type,data, plugins);
    };
    var getNewPlugins = function (type,data, plugins) {
        var params= {};
        if (
                type === 'select' ||
                type === 'selects' ||
                type === 'checkboxs' ||
                type === 'radios' ||
                type === 'selectpicker' ||
                type === 'selectpickers'
                ) {
            params.list = data['list'];
            params.value = '';
        }
        var post = {
            name: data['name'],
            title: data['title'],
            value: data['value']
        };
        $.extend(true, post, data, params);
        post.type = type;
        $.ajax({
            url: 'formdesign/form/buildPlugins',
            type: 'post',
            async: true,
            data: post,
            success: function (json) {
                $(plugins).find('div.plugins').html(json.data);
            }
        });
    };
    var plugins = function (type, index, plugins, callback) {
        var iframe = Layer.getChildFrame('body', index);
        Layer.iframeAuto(index);
        if (type === 'html')
        {
            $(plugins).find('div.html').html($(iframe).find('#html').val());
        } else {
           save(iframe, plugins); 
        }
        callback && typeof (callback) === 'function' && callback();
    };
    return plugins;
});
